package com.hunlian.makelove.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hunlian.makelove.AppApplication;
import com.hunlian.makelove.BaseFragemt;
import com.hunlian.makelove.R;
import com.hunlian.makelove.activity.DetailActivity;
import com.hunlian.makelove.activity.MainActivity;
import com.hunlian.makelove.activity.WebActivity;
import com.hunlian.makelove.adapter.ListAdapterOppositeSex;
import com.hunlian.makelove.bean.Banner;
import com.hunlian.makelove.bean.Person;
import com.hunlian.makelove.bean.UserIdAndCompleteBean;
import com.hunlian.makelove.common.AppConfig;
import com.hunlian.makelove.common.Constants;
import com.hunlian.makelove.net.NetVisitCallback;
import com.hunlian.makelove.net.ServiceInterfaceDef;
import com.hunlian.makelove.net.api.BannerServiceVisit;
import com.hunlian.makelove.net.api.OppositeSexServiceVisit;
import com.hunlian.makelove.tools.MyToast;
import com.hunlian.makelove.view.AutoListView;
import com.hunlian.makelove.view.AutoListView.OnLoadListener;
import com.hunlian.makelove.view.AutoListView.OnRefreshListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

/**
 * 缘份
 *
 * @author zealjiang
 * @time 2016/6/28 12:40
 */
public class OppositeSexFrag extends BaseFragemt implements OnRefreshListener,
        OnLoadListener {

    private int mPageNumber;
    private MainActivity mActivity;
    private AutoListView mAutoListView;
    private int NoLoadType = AutoListView.REFRESH;
    // 当前页码
    private int mPageIndex = 1;
    private ArrayList<Person> mListPerson;
    private ListAdapterOppositeSex mAdapter;
    private OppositeSexFrag mSelf;
    private ViewGroup rootView;
    private int mCurloadDataNum = 0;
    private boolean mHasMoreData = true;
    /**
     * 用来记录当前选中状态 ,key是userId
     */
    private SparseArray<Boolean> mSelectState = new SparseArray<Boolean>();
    //banner
    private ImageView mIvMsg;
    private DisplayImageOptions mOptions_ad;
    private ImageLoader mImageLoader;
    private String mBannerUrl;
    private String mTitle;

    @Override
    public void onResume() {
        super.onResume();
        //如果在详情页发送了求电话，那么返回本列表时就要刷新
        if (Constants.DETAIL_REQUEST_PHONE) {
            //刷新列表
            loadData();
            //重置
            Constants.DETAIL_REQUEST_PHONE = false;
        }

        if (mIvMsg.getVisibility() == View.GONE) {
            getBannerInfo();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mSelf = this;

        // 设置在loading时的默认图片
        mOptions_ad = new DisplayImageOptions.Builder()
                .cacheInMemory(true).cacheOnDisk(true).build();
        mImageLoader = ImageLoader.getInstance();

        if (rootView == null) {
            mActivity = (MainActivity) this.getActivity();
            rootView = (ViewGroup) inflater.inflate(R.layout.frag_opposite_sex,
                    null);
            ImageButton mIbBack = (ImageButton) rootView.findViewById(R.id.back);
            mIbBack.setVisibility(View.GONE);
            TextView mTvTitle = (TextView) rootView.findViewById(R.id.title);
            mTvTitle.setText("异性");

            mAutoListView = (AutoListView) rootView.findViewById(R.id.listView);
            mAutoListView.setOnRefreshListener(mSelf);
            mAutoListView.setOnLoadListener(mSelf);
            mListPerson = new ArrayList<Person>();
            mAdapter = new ListAdapterOppositeSex(mActivity);
            mAdapter.setList(mListPerson);
            mAutoListView.setAdapter(mAdapter);
            mAdapter.setSelectedArray(mSelectState);

            mAutoListView.setResultSize(0);
            loadData();

            //banner
            mIvMsg = (ImageView) rootView.findViewById(R.id.iv_msg);
            mIvMsg.setVisibility(View.VISIBLE);
            setListener();

            getBannerInfo();

            mIvMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(mBannerUrl) == false) {
                        Intent intent = new Intent(mActivity, WebActivity.class);
                        //intent.putExtra("hideTitle",true);
                        intent.putExtra("title", mTitle);
                        intent.putExtra("url", mBannerUrl);
                        startActivity(intent);
                    }
                }
            });
        }

        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;
    }

    /**
     * 请求banner信息
     *
     * @author zealjiang
     * @time 2016/7/12 11:04
     */
    private void getBannerInfo() {

        if (!AppApplication.networkAvailable) {
            MyToast.showShort("没有网络");
            mIvMsg.setVisibility(View.GONE);
            return;
        }
        BannerServiceVisit visit = new BannerServiceVisit(mActivity);
        visit.setParamters(AppConfig.getInstance().getLoginedUserId());
        //System.out.println("banner请求参数：" + visit.getParamter());
        visit.getResult(new NetVisitCallback<Banner, Object>(mActivity) {

            @Override
            public void onSuccess(Banner bean) {

                if (bean == null) return;
                if ("1".equals(bean.getIfshow())) {
                    mImageLoader.displayImage(bean.getImgurl(), mIvMsg, mOptions_ad);
                    mBannerUrl = bean.getWeburl();
                    mTitle = bean.getTitle();
                    //System.out.println("mBannerUrl :"+mBannerUrl);
                    mIvMsg.setVisibility(View.VISIBLE);
                } else {
                    mIvMsg.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(String errorEvent, String message, Object obj) {
                mIvMsg.setVisibility(View.GONE);
            }

        });
    }

    private void setListener() {

        mAutoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //System.out.println("setListener"+position);

                if (mListPerson == null) return;
                if (mListPerson.size() >= position) {
                    if (position < 1)
                        return;
                    //获取是否已发送求电话
                    int userId = Integer.valueOf(mListPerson.get(position - 1).getUserId());
                    boolean boo = mSelectState.get(userId);

                    Intent intent = new Intent(mActivity, DetailActivity.class);
                    intent.putExtra("hasSendRequestPhone", boo);
                    intent.putExtra("from", "yuanfen");
                    intent.putExtra("tarId", mListPerson.get(position - 1).getUserId());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void loadData() {
        mPageIndex = 1;
        NoLoadType = AutoListView.REFRESH;
        request();
    }

    @Override
    public void onRefresh() {
        mPageIndex = 1;
        NoLoadType = AutoListView.REFRESH;
        request();
    }

    @Override
    public void onLoad() {

        NoLoadType = AutoListView.LOAD;
        request();
    }

    private void request() {
        if (!AppApplication.networkAvailable) {
            MyToast.showShort("没有网络");
            mAutoListView.onRefreshComplete();
            return;
        }
        createProgressDialog(mActivity);
        progressDialog.show();

        OppositeSexServiceVisit visit = new OppositeSexServiceVisit(mActivity);
        visit.setParamters(AppConfig.getInstance().getLoginedUserId(), ServiceInterfaceDef.RECORD_COUNT_PER_PAGE + "", mPageIndex + "");
        System.out.println("异性请求参数：" + visit.getParamter());
        visit.getResult(new NetVisitCallback<ArrayList<Person>, UserIdAndCompleteBean>(mActivity) {

            @Override
            public void onSuccess(ArrayList<Person> data) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                switch (NoLoadType) {
                    case AutoListView.REFRESH:
                        mAutoListView.onRefreshComplete();
                        if (mListPerson == null) return;
                        mListPerson.clear();
                        mSelectState.clear();
                        break;
                    case AutoListView.LOAD:
                        mAutoListView.onLoadComplete();
                        break;
                    default:
                        mAutoListView.onRefreshComplete();
                        if (mListPerson == null) return;
                        mListPerson.clear();
                        mSelectState.clear();
                        break;
                }
                if (data == null) return;

                mListPerson.addAll(data);
                for (int i = 0; i < data.size(); i++) {
                    mSelectState.put(Integer.valueOf(data.get(i).getUserId()), false);
                }

                mCurloadDataNum = data.size();
                if (mCurloadDataNum > 0) {
                    mPageIndex = mPageIndex + 1;
                }

                mAutoListView.setResultSize(data.size());
                mAdapter.notifyDataSetChanged();

            }

            @Override
            public void onFailure(String errorEvent, String message, UserIdAndCompleteBean userBean) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                switch (NoLoadType) {
                    case AutoListView.REFRESH:
                        mAutoListView.onRefreshComplete();
                        break;
                    case AutoListView.LOAD:
                        mAutoListView.onLoadComplete();
                        break;
                    default:
                        mAutoListView.onRefreshComplete();
                        break;
                }
                if (ServiceInterfaceDef.SERVICE_RETURN_FAIL.equals(errorEvent)) {
                    try {
                        if (userBean == null) {
                            return;
                        }
                        if ("false".equals(userBean.getHasUserId())) {
                            //Toast.makeText(mActivity,message,Toast.LENGTH_SHORT).show();
                            //清楚userId
                            AppConfig.getInstance().clearLoginedUserId();
                            //跳转到登录
                            skipToRegisterActivity(mActivity);
                        }
                        if ("false".equals(userBean.getHasComplete())) {
                            Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
                            //跳转到完善资料
                            skipToOrganizingDataActivity(mActivity);
                        }

                    } catch (Exception e) {

                    }
                }
            }

        });
    }


}
